package models;

import java.util.*;

import javax.persistence.*;

import play.data.validation.Required;
import play.db.jpa.*;

/**
 * 
 * @author Islam Al-aarag
 * @version 1.0
 * 
 */
@Entity
public class Role extends Model {
	@Required
	@Lob
	public String description;
	@ManyToMany
	public List<Permission> allowedPermissions;
	@OneToMany(mappedBy = "role", cascade = CascadeType.PERSIST)
	public List<RoleInOrganization> usersAndOrganizations;
	@OneToMany(mappedBy = "role", cascade = CascadeType.PERSIST)
	public List<RoleInEntity> usersAndEntities;

	/**
	 * 
	 * @param description
	 *            description of the role(e.g: its allowed actions)
	 */

	public Role(String description) {
		this.description = description;
		allowedPermissions = new ArrayList<Permission>();
		usersAndOrganizations = new ArrayList<RoleInOrganization>();
		usersAndEntities = new ArrayList<RoleInEntity>();
	}

	public static Role findOrCreate(String description) {
		Role r = Role.find("byDescription", description).first();
		if (r == null) {
			r = new Role(description);
		}

		return r;
	}

	public Role addUserAndOrganization(RoleInOrganization userAndOrganization) {
		this.usersAndOrganizations.add(userAndOrganization);
		this.save();
		return this;
	}

	public Role addUserAndEntity(RoleInEntity userAndEntity) {
		this.usersAndEntities.add(userAndEntity);
		this.save();
		return this;
	}

	/**
	 * @author Ahmed Mahmoud
	 * @return
	 * @ManyToMany public List<Permission> allowedPermissions;
	 * @OneToMany(mappedBy = "role", cascade = CascadeType.PERSIST) public
	 *                     List<RoleInOrganization> usersAndOrganizations;
	 * @OneToMany (mappedBy= "role", cascade = CascadeType.PERSIST) public
	 *            List<RoleInEntity> usersAndEntities;
	 */
	public boolean cascadeDelete() {
		while (!usersAndOrganizations.isEmpty()) {
			RoleInOrganization roleInOrganization = usersAndOrganizations
					.get(0);
			roleInOrganization.cascadeDelete();
		}
		while (!usersAndEntities.isEmpty()) {
			RoleInEntity roleInEntity = usersAndEntities.get(0);
			roleInEntity.cascadeDelete();
		}
		this.delete();
		return true;
	}
}
